#!/data/data/com.termux/files/usr/bin/bash

# 避免在 PRoot 环境中运行时产生冲突或错误行为
fix_profile() {
    if [ -f ${DESTINATION}/root/.bash_profile ]; then
        sed -i '/if/,/fi/d' "${DESTINATION}/root/.bash_profile"
    fi
}

# 配置kali 
fix_sudo() {
    chmod +s $DESTINATION/usr/bin/sudo
    chmod +s $DESTINATION/usr/bin/su
    echo "kali    ALL=(ALL:ALL) ALL" > $DESTINATION/etc/sudoers.d/kali
    echo "Set disable_coredump false" > $DESTINATION/etc/sudo.conf
}

# 同步termux和kali的用户
fix_uid() {
    GID=$(id -g)
    startkali -r usermod -u $UID kali 2>/dev/null
    startkali -r groupmod -g $GID kali 2>/dev/null
}

# 为kali创建vnc脚本
create_xsession_handler() {
    if [ $SETARCH = "arm64" ]; then
        LIBGCCPATH=/usr/lib/aarch64-linux-gnu
    else
        LIBGCCPATH=/usr/lib/arm-linux-gnueabihf
    fi
    VNC_WRAPPER=$DESTINATION/usr/bin/vnc
    cat > $VNC_WRAPPER <<- EOF
#!/bin/bash
    
vnc_start() {
    if [ ! -f ~/.vnc/passwd ]; then
        vnc_passwd
    fi
    USR=\$(whoami)
    if [ \$USR = "root" ]; then
        SCR=:1
    else
        SCR=:2
    fi
    export USER=\$USR; LD_PRELOAD=$LIBGCCPATH/libgcc_s.so.1 nohup vncserver \$SCR >/dev/null 2>&1 </dev/null
}

vnc_stop() {
    vncserver -kill :1
    vncserver -kill :2
    return \$?
}

vnc_passwd() {
    vncpasswd
    return \$?
}

vnc_status() {
    session_list=\$(vncserver -list)
    if [[ \$session_list == *"590"* ]]; then
        echo "\$session_list"
    else
        echo "there is nothing to list :)"
        echo "you can start a new session by << vnc start >>"
    fi
}

vnc_kill() {
    pkill Xtigervnc
    return \$?
}

case "\$1" in
    start)
        vnc_start
        ;;
    stop)
        vnc_stop
        ;;
    status)
        vnc_status
        ;;
    kill)
        vnc_kill
        ;;
    *)
        echo "[!] invalid input [start\stop\status\kill]"
esac
EOF
chmod +x $VNC_WRAPPER
}

# 更换为阿里云镜像源
set_aliyun_sources() {
    
    cat > ${DESTINATION}/etc/apt/sources.list <<- EOF
# 阿里云 Kali 源
deb http://mirrors.aliyun.com/kali kali-rolling main non-free contrib
deb-src http://mirrors.aliyun.com/kali kali-rolling main non-free contrib
EOF

    unset LD_PRELOAD

    proot --link2symlink \
    -r "$DESTINATION" \
    -b /dev -b /proc -b /sys \
    -w /root \
    /usr/bin/env -i \
        HOME=/root \
        TERM="$TERM" \
        PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
    sh <<'EOF'

    echo "[+] 下载并添加 Kali 官方 GPG 密钥..."
    curl https://archive.kali.org/archive-keyring.gpg -o /usr/share/keyrings/kali-archive-keyring.gpg  

    if [ $? -eq 0 ]; then
        echo "[+] 成功导入 Kali GPG 密钥"
    else
        echo "[-] 导入密钥失败，请检查网络连接"
        exit 1
    fi
EOF

}

## Main

fix_profile
fix_sudo
fix_uid
set_aliyun_sources
create_xsession_handler
